package com.sam.thread;

import com.google.common.collect.Maps;
import com.sam.listener.DataExtractScheduleEvent;
import com.sam.listener.JobWorkEvent;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

@Slf4j
@Data
public abstract class AbstractJobRunner<T> implements Callable<T> {

    private ApplicationContext applicationContext;
    private List<String> parentJobNames;
    private CountDownLatch countDownLatch;
    private String jobName;
    /**
     * 0： 未启动
     * 1：执行成功
     * -1：执行失败
     * 2：运行中
     */
    private Integer status = 0;

    public void setCountDownLatch(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    public void setApplicationContext(ApplicationContext context) {
        this.applicationContext = context;
    }

    public Integer getStatus() {
        return status;
    }

    public abstract String getJobName();

    public abstract T jobRun() throws Exception;

    @Override
    public T call() throws Exception {
        T t = null;
        try {
            status = 2;
            JobRunnerStatus.threadLocal.get().put(getJobName(), status);
            this.jobName = getJobName();
            log.info("job name: " + jobName + " 开始");
            t = this.jobRun();
            log.info("job name: " + jobName + " 结束");
            status = 1;
            JobRunnerStatus.threadLocal.get().put(getJobName(), status);
        } catch (Exception e) {
            status = -1;
            JobRunnerStatus.threadLocal.get().put(getJobName(), status);
            log.error("线程执行异常. {}", e.getMessage(), e);
        } finally {
            //Long l = countDownLatch.getCount();
            countDownLatch.countDown();  // 这个不管是否异常都需要数量减,否则会被堵塞无法结束

            Map map = Maps.newHashMap();
            map.put("jobName" , jobName);
            map.put("status" , status);
            applicationContext.publishEvent(new JobWorkEvent(map));
        }
        return t;
    }


}
